<script lang="ts" setup>
import { useToggle } from '@vueuse/core'

import { computed, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useCommentStore } from './stores/commentStore'
import { useArcoForm } from '@/composables/useArcoForm'
import type { FormRule } from '@/types/components-tool'
import { useUserStore } from '@/stores/user'
import { Role } from '@/constants/role'
import { useIssueStore } from '@/pages/HomePage/stores/issueStore'

const props = defineProps<{
  id: number
  targetName: string
  targetID: string
  issueID: number
  passed?: boolean
}>()

const [visible, toggleVisible] = useToggle()
const { formRef, formState, onValidateSuccess, validate } = useArcoForm({
  message: '',
  passed: props.passed ?? false
})

const userStore = useUserStore()

const isPending = ref(false)
const { addComment, repliedComment } = useCommentStore()

const issueStore = useIssueStore()
const isSelfIssue = computed(
  () => issueStore.searchIssueById(props.issueID)?.teacherID === userStore.user.username
)

onValidateSuccess(({ message, passed }) => {
  isPending.value = true

  setTimeout(() => {
    isPending.value = false
    toggleVisible(false)
    repliedComment(props.id)
    addComment({ ...props, hasReplied: true, message, passed })
    Message.success('发送成功')
  }, Math.random() * 1000)
})

const rules: FormRule<typeof formState.value> = {
  message: [{ required: true, message: '请输入回复信息' }]
}
</script>

<template>
  <a-button status="success" type="dashed" size="mini" @click="toggleVisible(true)">
    回复
    <a-modal
      hide-title
      :modal-style="{ padding: '0', width: '100%', maxWidth: '768px' }"
      :body-style="{ paddingBottom: '0' }"
      :ok-loading="isPending"
      ok-text="回复"
      :visible
      @ok="validate"
      @cancel="toggleVisible(isPending)"
    >
      <a-form ref="formRef" size="small" layout="vertical" :model="formState" :rules>
        <a-form-item field="name" label="回复消息">
          <a-input v-model.trim="formState.message" :max-length="64" show-word-limit />
        </a-form-item>
        <a-form-item v-show="isSelfIssue" field="passed" label="是否学生通过请求">
          <a-checkbox v-model="formState.passed">通过请求</a-checkbox>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-button>
</template>
